package cn.zwy.day2;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;

public class AddFieldAdapter extends ClassVisitor {

    /**
     * 字段修饰符
     */
    private int fAcc;

    /**
     * 字段名称
     */
    private String fName;

    /**
     * 字段描述符
     */
    private String fDesc;

    /**
     * 字段是否已经包含
     */
    private boolean isFieldPresent;

    public AddFieldAdapter(ClassVisitor cv, int fAcc, String fName, String fDesc) {
        super(Opcodes.ASM6, cv);
        this.fAcc = fAcc;
        this.fName = fName;
        this.fDesc = fDesc;
    }

    @Override
    public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
        // 判断是否包含指定名称的字段信息
        if (name.equals(fName)) {
            isFieldPresent = true;
        }
        if (name.equals("removeField")) {
            // do not delegate to next visitor -> this removes the field
            return null;
        }
        return super.visitField(access, name, desc, signature, value);
    }

    @Override
    public void visitEnd() {
        // 如果不包含某个字段
        if (!isFieldPresent) {
            FieldVisitor fv = super.visitField(fAcc, fName, fDesc, null, null);
            if (fv != null) {
                fv.visitEnd();
            }
        }
        super.visitEnd();
    }
}
